/**
 * 
 */
package com.ge.healthcare.autosc.onwatch.controller.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.ge.healthcare.autosc.common.ASCLogger;
import com.ge.healthcare.autosc.common.ASCUtil;
import com.ge.healthcare.autosc.common.util.ApplicationInfo;
import com.ge.healthcare.autosc.common.util.PropertyConstants;
import com.ge.healthcare.autosc.onwatch.service.IOnWatchService;
import com.ge.healthcare.autosc.onwatch.util.OnWatchConstants;

/**
 * @author 212042764
 * 
 */
public class DispatcherServletFilter implements Filter {

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		// Do Nothing
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		if (!ApplicationInfo.getInstance().getBooleanProperty(
				PropertyConstants.IIP4_DOC_FILTER_ENABLED, "true")) {
			chain.doFilter(request, response);
			return;
		}
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		if (!ASCUtil.isNullOrEmpty(httpRequest.getHeader("iipVersion"))) {
			if (this.isAllowedForTransfer((HttpServletRequest) request)) {
				chain.doFilter(request, response);
			} else {
				ASCLogger
						.error("Blocking request not allowed for transfer. Details:\n"
								+ this.getInfo(request));
			}
		} else {
			ASCLogger
					.info(this.getClass(), "doFilter",
							"Blocking request as iip version was not present in the header");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		// Do nothing
	}

	/**
	 * Checks to see if the file name is in the blocked list or not
	 * 
	 * @param request
	 * @param thf
	 * @return
	 */
	private boolean isAllowedForTransfer(HttpServletRequest request) {
		if (!OnWatchConstants.PRODIAGS_REQUEST_TYPE.equalsIgnoreCase(request
				.getHeader("requestType"))) {
			return true;
		}
		IOnWatchService service = (IOnWatchService) ApplicationInfo
				.getApplicationContext().getBean("onWatchService");
		if (this.hasRequirdParameters(request)) {
			return service.isAllowedForTransfer(request.getHeader("systemId"),
					request.getHeader("requestType").toUpperCase(),
					request.getHeader("filename"),
					request.getHeader("serviceId"),
					request.getHeader("createdBy"));
		} else {
			return false;
		}
	}

	/**
	 * Checks to see if the request had the required parameters
	 * 
	 * @param request
	 * @return
	 */
	private boolean hasRequirdParameters(HttpServletRequest request) {
		String methodName = "hasRequirdParameters";
		boolean hasRequiredParameters = true;
		;
		if (ASCUtil.isNullOrEmpty(request.getHeader("systemId"))) {
			ASCLogger.error(this.getClass(), methodName,
					"System id not present in request header");
			hasRequiredParameters = false;
		}
		if (ASCUtil.isNullOrEmpty(request.getHeader("requestType"))) {
			ASCLogger.error(this.getClass(), methodName,
					"Request Type not present in request header");
			hasRequiredParameters = false;
		}
		if (ASCUtil.isNullOrEmpty(request.getHeader("filename"))) {
			ASCLogger.error(this.getClass(), methodName,
					"File Name not present in request header");
			hasRequiredParameters = false;
		}
		if (ASCUtil.isNullOrEmpty(request.getHeader("serviceId"))) {
			ASCLogger.error(this.getClass(), methodName,
					"Service Id not present in request header");
			hasRequiredParameters = false;
		}
		if (ASCUtil.isNullOrEmpty(request.getHeader("createdBy"))) {
			ASCLogger.error(this.getClass(), methodName,
					"Created By not present in request header");
			hasRequiredParameters = false;
		}
		return hasRequiredParameters;
	}

	/**
	 * Print request Info
	 * 
	 * @param inRequest
	 * @throws ServletException
	 * @throws IOException
	 */
	public String getInfo(ServletRequest inRequest) throws ServletException,
			IOException {
		StringBuilder builder = new StringBuilder();
		HttpServletRequest request = (HttpServletRequest) inRequest;
		Enumeration<String> headers = request.getHeaderNames();
		while (headers.hasMoreElements()) {
			String name = headers.nextElement();
			builder.append(
					String.format("Header Name:%s Value:%s", name,
							request.getHeader(name))).append("\n");
		}
		Enumeration<String> attributes = request.getAttributeNames();
		while (attributes.hasMoreElements()) {
			String name = attributes.nextElement();
			builder.append(
					String.format("Attribute Name:%s Value:%s", name,
							request.getAttribute(name))).append("\n");
		}
		Enumeration<String> parameters = request.getParameterNames();
		while (parameters.hasMoreElements()) {
			String name = parameters.nextElement();
			builder.append(
					String.format("Parameter Name:%s Value:%s", name,
							request.getParameter(name))).append("\n");
		}
		return builder.toString();
	}

}
